package leetcode;

public class LeetCode38 {


    public static void main(String[] args) {
        LeetCode38 leetCode38 = new LeetCode38();
        System.out.println(leetCode38.countAndSay(6));
    }

    StringBuilder tmp = new StringBuilder();

    public String countAndSay(int n) {
        StringBuilder sb = new StringBuilder("1");
        for (int i = 2, j = 0; i <= n; i++, j = 0) {
            while (j < sb.length()) {
                j = getNextIndex(sb, j);
            }
            sb.setLength(0);
            sb.append(tmp);
            tmp.setLength(0);
        }
        return sb.toString();
    }

    private int getNextIndex(StringBuilder str, int index) {
        char c = str.charAt(index);
        int count = 0, startIndex = index;
        while (index < str.length()) {
            if (str.charAt(index) != c)
                break;
            index++;
            count++;
        }
        tmp.append(count).append(c);
        return count + startIndex;
    }
//------------------------------------------------------------------
}
